package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步保存搜索记录
     */
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDto userSearchDto) {
        ApBehaviorEntry apBehaviorEntry = getApBehaviorEntry(userSearchDto.getEntryId(), userSearchDto.getEquipmentId());
        //判断数据库中有无当前记录
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
                .and("keyword").is(userSearchDto.getSearchWords()));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch == null) {
            //有当前记录则更新时间  没有当前关键字记录则创建
            apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(userSearchDto.getSearchWords());
        }
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 获取当前行为实体
     */
    private ApBehaviorEntry getApBehaviorEntry(Integer entryId, Integer eid) {
        //获取当前的行为实体
        ResponseResult<ApBehaviorEntry> res = behaviorFeign.findByUserIdOrEquipmentId(entryId, eid);
        if (res.getCode() != 0) {
            log.error("behaviorFeign 远程调用 findByUserIdOrEquipmentId失败，错误原因：{}，参数：{}，{}", res.getErrorMessage(), entryId, eid);
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "获取行为实体失败！");
        }
        ApBehaviorEntry apBehaviorEntry = res.getData();
        if (apBehaviorEntry == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前行为实体不存在");
        }
        return apBehaviorEntry;
    }

    /**
     * 加载搜索记录
     */
    @Override
    public ResponseResult getSearchRecodes(UserSearchDto dto) {
        // 检查参数
        if (dto.getPageNum() < 1) {
            dto.setPageNum(5);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取当前行为实体
        ApBehaviorEntry apBehaviorEntry = getApBehaviorEntry(user.getId(), dto.getEquipmentId());
        // 构造查询条件
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
                .and("createdTime").lt(dto.getMinBehotTime()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getPageSize());
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);

    }

    /**
     * 删除历史记录
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //检查参数
        if (dto.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取当前行为实体
        ApBehaviorEntry apBehaviorEntry = getApBehaviorEntry(user.getId(), dto.getEquipmentId());
        //判断有无当前记录
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
                .and("_id").is(dto.getId()));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前历史记录不存在！！！");
        }
        //执行删除
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
